﻿using AutoMapper;
using Mysoft.Common.Attributes.AutoMapping;
using Mysoft.Dto.Basic;
using System.Reflection;

namespace Mysoft.AppStartup.Container
{
    /// <summary>
    /// AutoMapper映射配置
    /// </summary>
    public class AutoMapperProfile : Profile
    {
        public AutoMapperProfile()
        {
            Dictionary<string, string> maps = new Dictionary<string, string>();
            var typeList = Assembly.GetAssembly(typeof(DtoBase)).GetTypes().Where(m => m.GetTypeInfo().BaseType != null && m.BaseType == (typeof(DtoBase))).ToList();
            //.Where(t => t.GetCustomAttributes(typeof(TypeMapperAttribute)).Any()).ToList();
            typeList.ForEach(type =>
            {
                //获取类指定的特性
                var attribute = (CreateMapperAttribute)type.GetCustomAttributes(typeof(CreateMapperAttribute)).FirstOrDefault();
                if (attribute == null || attribute.SourceType == null)
                    return;
                attribute.SourceType.ToList().ForEach(SourceType =>
                {
                    string entityKey = type.Name + SourceType.Name;
                    string dtoKey = SourceType.Name + type.Name;
                    if (!maps.ContainsKey(entityKey) && !maps.ContainsKey(dtoKey))
                    {
                        maps.Add(entityKey, dtoKey);
                        maps.Add(dtoKey, entityKey);

                        //类映射
                        var mapEntity = CreateMap(type, SourceType);
                        var mapDto = CreateMap(SourceType, type);
                    }
                });
            });
        }
    }
}
